﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Checkpoint2XNA.Models.Chess
{
    public class Knight : Model3D
    {
        const float BOX_SIZE = .5f;
        const float BOX_SHRINK = .7f;
        const int NUM_BOXES = 3;

        public Box[] Boxes;

        public Knight(Vector3 p, float size, ChessSide c): base(p, c)
        {
            Boxes = new Box[NUM_BOXES];

            var boxSize = BOX_SIZE * size;
            float sumSize = 0;
            for (int i = 0; i < NUM_BOXES; i++)
            {
                Boxes[i] = new Box(new Vector3(p.X, p.Y + sumSize, p.Z), boxSize, boxSize, boxSize, Color);
                sumSize += boxSize;
                boxSize *= BOX_SHRINK;
            }
        }

        public override void MoveTo(Vector3 point)
        {
            var lowY = Boxes[0].MinCorner.Y;
            for (int i = 0; i < NUM_BOXES; i++)
            {
                Boxes[i].MoveTo(new Vector3(point.X, point.Y + Boxes[i].MinCorner.Y - lowY, point.Z));
            }
            CenterBottom = point;
        }

        public override Microsoft.Xna.Framework.Color GetColorAt(Microsoft.Xna.Framework.Vector3 point)
        {
            return Color;
        }

        public override Microsoft.Xna.Framework.Vector3 GetNormal(Microsoft.Xna.Framework.Vector3 point)
        {
            for (int i = 0; i < NUM_BOXES - 1; i++)
            {
                if (point.Y <= Boxes[i].MaxCorner.Y + 1E-6)
                    return Boxes[i].GetNormal(point);
            }

            return Boxes[NUM_BOXES - 1].GetNormal(point);
        }

        public override double RayCollide(Microsoft.Xna.Framework.Vector3 origin, Microsoft.Xna.Framework.Vector3 normalVector)
        {
            var t = Double.MaxValue;
            var inv = new Vector3(1.0f / normalVector.X, 1.0f / normalVector.Y, 1.0f / normalVector.Z);
            for (int i = 0; i < NUM_BOXES; i++)
            {
                double temp;
                if ((temp = Boxes[i].BetterRayCollide(origin, normalVector, inv)) > 0 && temp < t)
                    t = temp;
            }

            return t == Double.MaxValue ? -1 : t;
        }
    }
}
